package org.hibernate.tool.ant;

import javax.persistence.Entity;

import net.sourceforge.sannotations.utils.Scanner;

import org.apache.tools.ant.BuildException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.util.ReflectHelper;

/**
 * Created on: 2007/10/15
 *
 * @author Alan She(scw1109)
 */
public class AutoAnnotationConfigurationTask extends ConfigurationTask {

    public AutoAnnotationConfigurationTask() {
        setDescription("Lego enhanced Auto Hibernate Annotation/EJB3 Configuration");
    }

    protected Configuration createConfiguration() {
        try {
            Class clazz = ReflectHelper.classForName("org.hibernate.cfg.AnnotationConfiguration",
                    AutoAnnotationConfigurationTask.class);
            AnnotationConfiguration cfg = (AnnotationConfiguration) clazz.newInstance();
            autoAddEntityClasses(cfg);
            return cfg;
        }
        catch (Throwable t) {
            throw new BuildException("Problems in creating a AnnotationConfiguration. Have you remembered to add it to the classpath ?",
                    t);
        }
    }

    private void autoAddEntityClasses(AnnotationConfiguration config) {
        final AnnotationConfiguration annConfig = config;
        final Scanner sc = new Scanner();
        for (final Class<?> c : sc.getClasses()) {
            if (c.getAnnotation(Entity.class) != null) {
                log("Founded entity class: " + c.getName());
                annConfig.addAnnotatedClass(c);
            }
        }
    }

    protected void validateParameters() throws BuildException {
        super.validateParameters();
    }
}
